﻿using DTCash.Logger;
using DTCash.Logger.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web.Http;
using DTCash.Redis;
using Uranus.Common;
using Uranus.Service.OtherService;
using Uranus.Service.UserService;
using Uranus.WeiStationAPI.App_Start;
using Uranus.WeiStationAPI.Common;
using Uranus.WeiStationAPI.Models;


namespace Uranus.WeiStationAPI.Controllers
{
    public class SafetyController : BaseController
    {

        #region 登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultResPonse Login()
        {
            string mobile = GetParmsKey<string>("mobile");
            string password = GetParmsKey<string>("password");
            string alijstoken = GetParmsKey<string>("alijstoken");
            string wxguid = GetParmsKey<string>("wx_guid");
            if (string.IsNullOrEmpty(mobile))
            {
                resultResPonse.code = 101;
                return Send(resultResPonse);
            }
            else if (string.IsNullOrEmpty(password))
            {
                resultResPonse.code = 102;
                return Send(resultResPonse);
            }
            int enabledAliPrevention = Validates.GetInt(ConfigCenterWork.GetConfigValueByOperationType(2) ?? 2);
            if (string.IsNullOrEmpty(alijstoken) && enabledAliPrevention == 2)
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            try
            {
                UserResponse userRes = Uranus.Service.User.GetUser().UserLogin(new UserRequest() { UserDto = new UserDTO() { Mobile = mobile, PassWord = password } }) ?? new UserResponse();
                if (userRes.Code == 1)
                {
                    if (!CommonModel.EnDebug & !CommonModel.AliLoginPrevention(alijstoken, mobile, mobile, visitDTO.UserHostAddress, 1, 1))
                    {
                        resultResPonse.code = 12;
                    }
                    else
                    {
                        int uid = userRes.UserDto.UserID;
                        resultResPonse.code = 1;

                        UserInfo = GetUserInfoByUserID(uid); //获取用户信息
                        UserLoginState user = new UserLoginState(uid);
                        #region 下线其它客户端

                        string key = string.Format("OtherOther{0}|LoginState", UserInfo.UserID);
                        List<string> list = CacheRedis.GetAllKey();
                        list = list.Where(a => a.StartsWith(key)).ToList();
                        for (int i = 0; i < list.Count; i++)
                        {
                            string ext = list[i].Substring(list[i].IndexOf('-') + 1,
                                                           list[i].LastIndexOf('-') - list[i].IndexOf('-') - 1);
                            UserInfo oldInfo =
                                CacheRedis.GetCache(
                                    CacheItem.InitByIdentity(UserInfo.UserID.ToString(), "LoginState", ext).Other.other)
                                as UserInfo;
                            if (oldInfo != null)
                            {
                                oldInfo.LoginState = false;
                                CacheRedis.AddCache(new TimeSpan(240, 0, 0),
                                                    CacheItem.InitByIdentity(UserInfo.UserID.ToString(), "LoginState", ext)
                                                             .Other.other, oldInfo);
                            }
                        }

                        #endregion
                        #region 绑定微信

                        if (!string.IsNullOrEmpty(wxguid))
                        {
                            string result = RequestCommon.SimulationHttp(CommonModel.WxRequestUrl, string.Format("cmdid=getuseridbyguid&guid={0}", wxguid), "post");
                            HttpRequestReuslt shortData = CodeCommon.DeSerialize<HttpRequestReuslt>(result);
                            if (shortData.code == 1)
                            {
                                if (string.IsNullOrEmpty(shortData.extendData) || shortData.extendData.Equals("0"))
                                {
                                    string ress = RequestCommon.SimulationHttp(CommonModel.WxRequestUrl, string.Format("cmdid=bindwxuserinfo&userid={0}&guid={1}", userRes.UserDto.UserID, wxguid), "post");
                                    HttpRequestReuslt shortDatas = CodeCommon.DeSerialize<HttpRequestReuslt>(ress);
                                    if(shortDatas.code != 1) { 
                                        LogHelper.WriteLogInfo(string.Format("用户{0}绑定微信{1}", UserInfo.UserID, shortDatas.code == 1), "结果描述:" + shortDatas.desc, false);
                                    }
                                }
                            }
                        }
                        #endregion
                        UserInfo.LoginState = true;
                        SaveUser(UserInfo, user);
                        string gid = "_" + user.EnKey;
                        SourceHandle(SourceOperation.Login, string.Empty, uid, Uranus.Common.Validates.GetInt(GetParmsKey<string>("sourceTypeId")));
                        resultResPonse.data = new
                        {
                            gid = gid,
                            UserInfo = new
                            {
                                IDCard = Uranus.Common.Validates.SetHideIDCard(UserInfo.IDCard),
                                Email = UserInfo.Email,
                                EmailAuthStatusID = UserInfo.EmailAuthStatusID,
                                CashFreezePrice = UserInfo.CashFreezePrice,
                                InvestFreezePrice = UserInfo.InvestFreezePrice,
                                DQAllInvestedPrice = UserInfo.DQAllInvestedPrice,
                                DQPredictEarning = UserInfo.DQPredictEarning,
                                DQInvestingPrice = UserInfo.DQInvestingPrice,
                                DQEarning = UserInfo.DQEarning,
                                UsablePrice = UserInfo.UsablePrice,
                                Mobile = UserInfo.Mobile,
                                MobileAuthStatusID = UserInfo.MobileAuthStatusID,
                                FullName = UserInfo.FullName,
                                InvitationCode = UserInfo.InvitationCode,
                                IDCardAuthStatusID = UserInfo.IDCardAuthStatusID,
                                HuiFuCode = UserInfo.HuiFuCode
                            }
                        };
                    }

                }
                else
                {
                    ////阿里登录安全防护
                    if (userRes.Code != 0)
                    {
                        CommonModel.AliLoginPrevention(alijstoken, mobile, mobile, visitDTO.UserHostAddress, 0, 0);
                    }
                    if (userRes.Code == 3 || userRes.Code == 5)
                    {
                        //resultResPonse.code = 113;//手机号尚未注册
                        resultResPonse.code = 0;
                        resultResPonse.data = "手机号或密码不正确";
                    }
                    else
                    {
                        resultResPonse.code = 0;
                        resultResPonse.data = "登录失败，请稍后再试";
                        LogHelper.WriteLogError("用户" + mobile + "登录失败", "失败原因:" + userRes.ResposeData, false);
                    }
                }
            }
            catch (Exception ex)
            {
                resultResPonse.code = 0;
                resultResPonse.data = "登录失败，请稍后再试";
                LogHelper.WriteLogError("用户" + mobile + "登录失败", "失败原因:" + ex.Message, false);
            }
            return Send(resultResPonse);
        }
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse LoginOut()
        {
            UserQuit();
            CacheRedis.DelCacheKey(CacheItem.InitByIdentity(UserInfo.UserID.ToString()).User.Info);
            CacheRedis.DelCacheKey(CacheItem.InitByIdentity(UserInfo.UserID.ToString()).User.Price);
            resultResPonse.code = 1;
            return Send(resultResPonse);
        }
        #endregion

        #region 微信功能

        /// <summary>
        /// 微信绑定
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultResPonse WxBinding()
        {
            string mobile = GetParmsKey<string>("mobile");
            string password = GetParmsKey<string>("password");
            string wxguid = GetParmsKey<string>("wx_guid");
            string alijstoken = GetParmsKey<string>("alijstoken");
            if (string.IsNullOrEmpty(mobile))
            {
                resultResPonse.code = 101;
                return Send(resultResPonse);
            }
            else if (string.IsNullOrEmpty(password))
            {
                resultResPonse.code = 102;
                return Send(resultResPonse);
            }
            int enabledAliPrevention = Validates.GetInt(ConfigCenterWork.GetConfigValueByOperationType(2) ?? 2);
            if (string.IsNullOrEmpty(alijstoken) && enabledAliPrevention == 2 && string.IsNullOrEmpty(wxguid))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            try
            {
                UserResponse userRes = Uranus.Service.User.GetUser().UserLogin(new UserRequest() { UserDto = new UserDTO() { Mobile = mobile, PassWord = password } }) ?? new UserResponse();
                if (userRes.Code == 1)
                {
                    if (!CommonModel.EnDebug & !CommonModel.AliLoginPrevention(alijstoken, mobile, mobile, visitDTO.UserHostAddress, 1, 1))
                    {
                        resultResPonse.code = 12;
                    }
                    else
                    {
                        //int uid = userRes.UserDto.UserID;
                        //resultResPonse.code = 1;
                        //resultResPonse.data = uid;
                        //绑定微信
                        string result = RequestCommon.SimulationHttp(CommonModel.WxRequestUrl, string.Format("cmdid=bindwxuserinfo&userid={0}&guid={1}", userRes.UserDto.UserID, wxguid), "post");
                        HttpRequestReuslt shortData = CodeCommon.DeSerialize<HttpRequestReuslt>(result);
                        if (shortData.code == 1)
                        {
                            resultResPonse.code = 1;
                        }
                        else if (shortData.code == 4)
                        {
                            resultResPonse.code = 5;
                            resultResPonse.data = "链接失效";
                            LogHelper.WriteLogInfo("用户微信绑定失败", "失败结果：链接失效,返回" + result, wxguid);
                        }
                        else
                        {
                            LogHelper.WriteLogInfo("用户微信绑定失败", "失败结果：" + result, wxguid);
                            resultResPonse.code = 0;
                            resultResPonse.data = shortData.desc;
                        }
                    }
                }
                else
                {
                    ////阿里登录安全防护
                    if (userRes.Code != 0)
                    {
                        CommonModel.AliLoginPrevention(alijstoken, mobile, mobile, visitDTO.UserHostAddress, 0, 0);
                    }
                    if (userRes.Code == 3 || userRes.Code == 5)
                    {
                        //resultResPonse.code = 113;//手机号尚未注册
                        resultResPonse.code = 0;
                        resultResPonse.data = "手机号或密码不正确";
                    }
                    else
                    {
                        resultResPonse.code = 0;
                        resultResPonse.data = "绑定失败，请稍后再试";
                        LogHelper.WriteLogError("用户" + mobile + "绑定失败", "失败原因:" + userRes.ResposeData, false);
                    }
                }
            }
            catch (Exception ex)
            {
                resultResPonse.code = 0;
                resultResPonse.data = "绑定失败，请稍后再试";
                LogHelper.WriteLogError("用户" + mobile + "绑定失败", "失败原因:" + ex.Message, false);
            }
            return Send(resultResPonse);
        }

        /// <summary>
        /// 微信解除绑定
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse WxUnBinding()
        {
            string wxguid = GetParmsKey<string>("wx_guid");
            if (string.IsNullOrEmpty(wxguid))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            try
            {
                string url = string.Format("cmdid=wxunbinding&guid={0}&userid={1}", wxguid, UserInfo.UserID);
                LogHelper.WriteLogInfo("用户解除微信绑定", "URL:" + url);
                string result = RequestCommon.SimulationHttp(CommonModel.WxRequestUrl, url, "post");
                HttpRequestReuslt shortData = CodeCommon.DeSerialize<HttpRequestReuslt>(result);
                if (shortData.code == 1)
                {
                    resultResPonse.code = 1;
                    UserQuit();
                    CacheRedis.DelCacheKey(CacheItem.InitByIdentity(UserInfo.UserID.ToString()).User.Info);
                    CacheRedis.DelCacheKey(CacheItem.InitByIdentity(UserInfo.UserID.ToString()).User.Price);
                }
                else if (shortData.code == 4)
                {
                    resultResPonse.code = 5;
                    resultResPonse.data = "链接失效";
                    LogHelper.WriteLogInfo("用户微信绑定失败", "失败结果：链接失效,返回" + result, wxguid);
                }
                else
                {
                    LogHelper.WriteLogInfo("用户解除微信绑定失败", "失败结果：" + result, wxguid);
                    resultResPonse.code = 0;
                    resultResPonse.data = shortData.desc;
                }
            }
            catch (Exception ex)
            {
                resultResPonse.code = 0;
                resultResPonse.data = "微信解除绑定失败，请稍后再试";
                LogHelper.WriteLogError("用户编号：" + UserInfo.UserID + "guid：" + wxguid + "微信解除绑定失败", "失败原因:" + ex.ToString(), false);
            }
            return Send(resultResPonse);
        }

        /// <summary>
        /// 微信登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultResPonse WxLogin()
        {
            string wxguid = GetParmsKey<string>("wx_guid");

            if (string.IsNullOrEmpty(wxguid))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            try
            {
                string result = RequestCommon.SimulationHttp(CommonModel.WxRequestUrl, string.Format("cmdid=getuseridbyguid&guid={0}", wxguid), "post");
                HttpRequestReuslt shortData = CodeCommon.DeSerialize<HttpRequestReuslt>(result);
                if (shortData.code == 1)
                {
                    if (string.IsNullOrEmpty(shortData.extendData) || shortData.extendData.Equals("0"))
                    {
                        resultResPonse.code = 2;
                        return Send(resultResPonse);
                    }
                    int uid = int.Parse(shortData.extendData);
                    resultResPonse.code = 1;

                    UserInfo = GetUserInfoByUserID(uid); //获取用户信息
                    UserLoginState user = new UserLoginState(uid);
                    #region 下线其它客户端

                    string key = string.Format("OtherOther{0}|LoginState", UserInfo.UserID);
                    List<string> list = CacheRedis.GetAllKey();
                    list = list.Where(a => a.StartsWith(key)).ToList();
                    for (int i = 0; i < list.Count; i++)
                    {
                        string ext = list[i].Substring(list[i].IndexOf('-') + 1,
                            list[i].LastIndexOf('-') - list[i].IndexOf('-') - 1);
                        UserInfo oldInfo =
                            CacheRedis.GetCache(
                                    CacheItem.InitByIdentity(UserInfo.UserID.ToString(), "LoginState", ext).Other.other)
                                as UserInfo;
                        if (oldInfo != null)
                        {
                            oldInfo.LoginState = false;
                            CacheRedis.AddCache(new TimeSpan(240, 0, 0),
                                CacheItem.InitByIdentity(UserInfo.UserID.ToString(), "LoginState", ext)
                                    .Other.other, oldInfo);
                        }
                    }

                    #endregion

                    UserInfo.LoginState = true;
                    SaveUser(UserInfo, user);
                    string gid = "_" + user.EnKey;
                    SourceHandle(SourceOperation.Login, string.Empty, uid, Uranus.Common.Validates.GetInt(GetParmsKey<string>("sourceTypeId")));
                    resultResPonse.data = new
                    {
                        gid = gid,
                        UserInfo = new
                        {
                            IDCard = Uranus.Common.Validates.SetHideIDCard(UserInfo.IDCard),
                            Email = UserInfo.Email,
                            EmailAuthStatusID = UserInfo.EmailAuthStatusID,
                            CashFreezePrice = UserInfo.CashFreezePrice,
                            InvestFreezePrice = UserInfo.InvestFreezePrice,
                            DQAllInvestedPrice = UserInfo.DQAllInvestedPrice,
                            DQPredictEarning = UserInfo.DQPredictEarning,
                            DQInvestingPrice = UserInfo.DQInvestingPrice,
                            DQEarning = UserInfo.DQEarning,
                            UsablePrice = UserInfo.UsablePrice,
                            Mobile = UserInfo.Mobile,
                            MobileAuthStatusID = UserInfo.MobileAuthStatusID,
                            FullName = UserInfo.FullName,
                            InvitationCode = UserInfo.InvitationCode,
                            IDCardAuthStatusID = UserInfo.IDCardAuthStatusID,
                            HuiFuCode = UserInfo.HuiFuCode
                        }
                    };
                }
                else if (shortData.code == 4)
                {
                    resultResPonse.code = 5;
                    resultResPonse.data = "链接失效";
                    LogHelper.WriteLogInfo("用户微信登录失败", "失败结果：链接失效,返回" + result, wxguid);
                }
                else
                {
                    LogHelper.WriteLogInfo("用户微信登录失败", "失败结果：" + result, wxguid);
                    resultResPonse.code = 0;
                    resultResPonse.data = shortData.desc;
                }
            }
            catch (Exception ex)
            {
                resultResPonse.code = 0;
                resultResPonse.data = "微信登录失败，请稍后再试";
                LogHelper.WriteLogError("用户" + wxguid + "微信登录失败", "失败原因:" + ex.Message, false);
            }
            return Send(resultResPonse);
        } 
        #endregion

        #region 注册
        /// <summary> 
        /// 注册
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultResPonse Register()
        {
            string mobile = GetParmsKey<string>("mobile");
            string password = GetParmsKey<string>("password");
            string verifycode = GetParmsKey<string>("verifycode");
            string invitationcode = GetParmsKey<string>("invitationcode");
            string alijstoken = GetParmsKey<string>("alijstoken");
            string wxguid = GetParmsKey<string>("wx_guid");
            if (string.IsNullOrEmpty(mobile))
            {
                resultResPonse.code = 101;//用户名不能为空
                return Send(resultResPonse);
            }
            if (string.IsNullOrEmpty(password))
            {
                resultResPonse.code = 102;//密码不能为空
                return Send(resultResPonse);
            }
            if (string.IsNullOrEmpty(alijstoken))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            try
            {
                resultResPonse = VerifyMobileVerifyCodeByType(mobile, verifycode, "1");//验证短信是否正确
                if (resultResPonse.code != 1)
                {
                    return Send(resultResPonse);
                }
                //阿里注册安全防护验证
                if (!CommonModel.EnDebug & !CommonModel.AliRegisterPrevention(alijstoken, mobile, visitDTO.UserHostAddress))
                {
                    resultResPonse.code = 013;
                    return Send(resultResPonse);
                }
                UserResponse userRes = Uranus.Service.User.GetUser().RegisterUser(new UserRequest()
                {
                    UserDto = new UserDTO()
                    {
                        Mobile = mobile,
                        PassWord = password,
                        UserFromID = 0,
                        InvitationCode = invitationcode
                    }
                });
                if (userRes.Code == 1)
                {
                    CacheKey cacheKey = CacheItem.InitByIdentity(mobile, "registerverifycode").User.Other;
                    CacheRedis.DelCacheKey(cacheKey);

                    int uid = userRes.UserDto.UserID;
                    resultResPonse.code = 1; //注册成功
                    UserInfo = GetUserInfoByUserID(uid);//获取用户信息
                    UserLoginState user = new UserLoginState(uid);
                    UserInfo.LoginState = true;
                    SaveUser(UserInfo, user);
                    string gid = "_" + user.EnKey;
                    #region 绑定微信

                    if (!string.IsNullOrEmpty(wxguid))
                    {
                        string result = RequestCommon.SimulationHttp(CommonModel.WxRequestUrl, string.Format("cmdid=getuseridbyguid&guid={0}", wxguid), "post");
                        HttpRequestReuslt shortData = CodeCommon.DeSerialize<HttpRequestReuslt>(result);
                        if (shortData.code == 1)
                        {
                            if (string.IsNullOrEmpty(shortData.extendData) || shortData.extendData.Equals("0"))
                            {
                                string ress = RequestCommon.SimulationHttp(CommonModel.WxRequestUrl, string.Format("cmdid=bindwxuserinfo&userid={0}&guid={1}", userRes.UserDto.UserID, wxguid), "post");
                                HttpRequestReuslt shortDatas = CodeCommon.DeSerialize<HttpRequestReuslt>(ress);
                                LogHelper.WriteLogError(string.Format("用户{0}绑定微信{1}", UserInfo.UserID, shortDatas.code == 1), "结果描述:" + shortDatas.desc, false);
                            }
                        }
                    }
                    #endregion
                    SourceHandle(SourceOperation.Register, string.Empty, uid, Uranus.Common.Validates.GetInt(GetParmsKey<string>("sourceTypeId")));
                    resultResPonse.data = new
                    {
                        gid = gid,
                        UserInfo = new
                        {
                            IDCard = Uranus.Common.Validates.SetHideIDCard(UserInfo.IDCard),
                            Email = UserInfo.Email,
                            EmailAuthStatusID = UserInfo.EmailAuthStatusID,
                            CashFreezePrice = UserInfo.CashFreezePrice,
                            InvestFreezePrice = UserInfo.InvestFreezePrice,
                            DQAllInvestedPrice = UserInfo.DQAllInvestedPrice,
                            DQPredictEarning = UserInfo.DQPredictEarning,
                            DQInvestingPrice = UserInfo.DQInvestingPrice,
                            DQEarning = UserInfo.DQEarning,
                            UsablePrice = UserInfo.UsablePrice,
                            Mobile = UserInfo.Mobile,
                            MobileAuthStatusID = UserInfo.MobileAuthStatusID,
                            FullName = UserInfo.FullName,
                            InvitationCode = UserInfo.InvitationCode,
                            IDCardAuthStatusID = UserInfo.IDCardAuthStatusID,
                            HuiFuCode = UserInfo.HuiFuCode
                        }
                    };
                }
                else if (userRes.Code == 3)
                {
                    resultResPonse.code = 5; //用户已经存在
                    resultResPonse.data = userRes.ResposeData;
                }
                else
                {
                    resultResPonse.data = "注册失败，请稍后再试";
                    LogHelper.WriteLogError("用户" + mobile + "注册失败", "失败原因:" + userRes.ResposeData, false);
                    resultResPonse.code = 5;
                }
            }
            catch (Exception ex)
            {
                resultResPonse.data = "注册失败，请稍后再试";
                LogHelper.WriteLogError("用户" + mobile + "注册失败", "失败原因:" + ex.Message, false);
                resultResPonse.code = 5;
            }
            return Send(resultResPonse);
        }
        #endregion

        #region 短信发送(1注册 2修改密码 3找回密码 4更换手机号 5新手机号 )
        /// <summary>
        /// 根据类型获取 获取手机验证码
        /// Date:2017-10-19 00:00:00
        /// Author:Linsan
        /// </summary>
        /// <returns></returns>
        [HttpPost]

        [UserState(VisitUserStateEnum = VisitUserStateEnum.NoMustLogin)]
        public ResultResPonse GetMobileVerifyCodeByType()
        {
            string mobile = GetParmsKey<string>("mobile");
            string type = GetParmsKey<string>("type");
            string alijstoken = GetParmsKey<string>("alijstoken");
            if (string.IsNullOrEmpty(type))
            {
                resultResPonse.code = 003; //参数错误
                return Send(resultResPonse);
            }
            if (type == "2" || type == "4")
            {
                mobile = UserInfo.Mobile;
            }
            if (string.IsNullOrEmpty(mobile))
            {
                resultResPonse.code = 106; //请输入手机号
                return Send(resultResPonse);
            }
            Regex mobileReg = new Regex(@"^1{1}[3-9]{1}[0-9]{9}$", RegexOptions.IgnoreCase);
            if (!mobileReg.IsMatch(mobile))
            {
                resultResPonse.code = 105; //手机号格式不正确
                return Send(resultResPonse);
            }
            string rediskey = type == "1"
                                  ? "registersmscode"
                                  : type == "2"
                                        ? "updatepwdsmscode"
                                        : type == "3"
                                              ? "backpwdsmscode"
                                              : type == "4"
                                                    ? "updatephonesmscode"
                                                    : type == "5" ? "newphonesmscode" : "";
            if (string.IsNullOrEmpty(rediskey))
            {
                resultResPonse.code = 9;
                return Send(resultResPonse);
            }
            CacheKey smssCacheKey = CacheItem.InitByIdentity("smss", mobile, rediskey).Other.other;
            if (CacheRedis.ExistsRedis(smssCacheKey))
            {
                resultResPonse.code = 0;
                resultResPonse.data = "获取短信太频繁，请稍后再试";
                return Send(resultResPonse);
            }
            //阿里验证码安全防护验证
            if (!CommonModel.EnDebug & !CommonModel.AliMessagePrevention(alijstoken, mobile, type, visitDTO.UserHostAddress, visitDTO.UrlReferrer, visitDTO.UserAgent))
            {
                resultResPonse.code = 014;
                return Send(resultResPonse);
            }

            string code = string.Empty;//验证码 
            if (Common.CommonModel.EnDebug)
            {
                code = "11111";
            }
            else
            {
                code = new Random().Next(10000, 99999).ToString();
            }
            string message = string.Empty;//短信内容
            bool msgresult = false;//短信发送结果
            try
            {
                Dictionary<String, String> dic = new Dictionary<String, String>();
                CacheKey cacheKey = CacheItem.InitByIdentity(mobile, rediskey).User.Other;
                //防止短信发送延迟或用户接收延迟
                if (CacheRedis.ExistsRedis(cacheKey))
                {
                    dic = CacheRedis.GetCache(cacheKey) as Dictionary<String, String>;
                    code = dic["verifycode"];
                    CacheRedis.AddCache(new TimeSpan(0, 5, 0), cacheKey, dic);
                }
                else
                {
                    dic.Add("verifycode", code);
                    dic.Add("mobile", mobile);
                    CacheRedis.AddCache(new TimeSpan(0, 5, 0), cacheKey, dic);
                }
                if (type == "1") //获取注册验证码
                {
                    UserResponse userRes = Uranus.Service.User.GetUser().GetUserDTOByMobile(mobile);
                    if (userRes == null || userRes.Code == 2)
                    {
                        resultResPonse.code = 6;
                        return Send(resultResPonse);
                    }
                    if (userRes.Code == 1 && userRes.UserDto != null)
                    {
                        resultResPonse.code = 107;//手机号已经存在
                        return Send(resultResPonse);
                    }
                    message = string.Format("尊敬的用户，您正在注册爱聚财，请输入验证码{0}完成验证。切勿将验证码告知他人。", code);
                }
                else if (type == "2" || type == "3" || type == "4") //获取修改密码
                {
                    UserResponse userRes = Uranus.Service.User.GetUser().GetUserDTOByMobile(mobile);
                    if (userRes.Code == 1 && userRes.UserDto != null)
                    {
                        resultResPonse.code = 1;
                        if (type == "2")
                        {
                            message = string.Format("尊敬的用户，您正在修改登录密码，请输入验证码{0}完成验证。切勿将验证码告知他人。", code);
                        }
                        else if (type == "3")
                        {
                            message = string.Format("尊敬的用户，您正在修改登录密码，请输入验证码{0}完成验证。切勿将验证码告知他人。", code);
                        }
                        else if (type == "4")
                        {
                            message = string.Format("尊敬的用户，您正在修改登录手机号，请输入验证码{0}完成验证。切勿将验证码告知他人。", code);
                        }
                    }
                    else if (userRes.Code == 1 && userRes.UserDto == null)
                    {
                        resultResPonse.code = 5;
                        resultResPonse.data = "手机号不存在";
                        return Send(resultResPonse);
                    }
                    else
                    {
                        resultResPonse.code = 9;
                        return Send(resultResPonse);
                    }
                }
                else if (type == "5") //修改新手机号
                {
                    UserResponse userRes = Uranus.Service.User.GetUser().GetUserDTOByMobile(mobile);
                    if (userRes.Code == 1)
                    {
                        if (userRes.UserDto != null)
                        {
                            resultResPonse.code = 107;
                            return Send(resultResPonse);
                        }
                        else
                        {
                            resultResPonse.code = 1;
                        }
                    }
                    else
                    {
                        resultResPonse.code = 9;
                        return Send(resultResPonse);
                    }
                    message = string.Format("尊敬的用户，您正在修改登录手机号，请输入验证码{0}完成验证。切勿将验证码告知他人。", code);
                }


                //发送短信
                msgresult = Common.CommonModel.SendSmms("", mobile, message);
                if (msgresult)
                {
                    CacheKey smssCacheKey1 = CacheItem.InitByIdentity("smss", mobile, rediskey).Other.other;
                    CacheRedis.AddCache(new TimeSpan(0, 0, 50), smssCacheKey1, "true");
                }
                else
                {
                    resultResPonse.code = 0;
                    resultResPonse.data = "短信发送失败，请稍后再试";
                    return Send(resultResPonse);
                }
            }
            catch (Exception ex)
            {
                resultResPonse.code = 6;
                LogHelper.WriteLogError("获取验证码异常", string.Format("手机号{0}获取验证码{1}失败,错误原因：{2}", mobile, rediskey, ex.Message));
            }
            if (msgresult)
            {
                resultResPonse.code = 1;
                resultResPonse.data = true;
            }
            else
            {
                resultResPonse.code = 9; //获取短信验证码失败
            }
            return Send(resultResPonse);
        }


        /// <summary>
        /// 验证手机方法短信
        /// </summary>
        /// <param name="mobile">手机号码</param>
        /// <param name="pwd">密码</param>
        /// <param name="verifyCode">验证码</param>
        /// <returns></returns>
        private ResultResPonse VerifyMobileVerifyCodeByType(string mobile, string verifyCode, string type)
        {
            ResultResPonse res = new ResultResPonse();
            if (string.IsNullOrEmpty(type))
            {
                type = "1";
            }
            Dictionary<String, String> dic = new Dictionary<String, String>();
            //1注册 
            string rediskey = type == "1"
                                  ? "registersmscode"
                                  : type == "2"
                                        ? "updatepwdsmscode"
                                        : type == "3"
                                              ? "backpwdsmscode"
                                              : type == "4"
                                                    ? "updatephonesmscode"
                                                    : type == "5" ? "newphonesmscode" : "";
            CacheKey cacheKey = CacheItem.InitByIdentity(mobile, rediskey).User.Other;
            //if (type == "1" || type == "2")
            //{
            dic = CacheRedis.GetCache(cacheKey) as Dictionary<String, String>;
            //}
            if (dic == null || dic.Count == 0 || dic["verifycode"] == null || dic["verifycode"] == "")
            {
                res.code = 109; //请先获取短信验证码
                return res;
            }
            if (dic.Count > 0 && dic["verifycode"] != null && dic["verifycode"] == verifyCode)
            {
                CacheRedis.DelCacheKey(CacheItem.InitByIdentity("smss", mobile, rediskey).Other.other);
                res.code = 1;
                return res;
            }
            else
            {
                res.code = 111; //验证码错误
                return res;
            }
        }


        #endregion

        #region 修改登录密码
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse ModifyPassWord()
        {
            string verifycode = GetParmsKey<string>("verifycode");
            string password = GetParmsKey<string>("password");

            if (string.IsNullOrEmpty(verifycode))
            {
                resultResPonse.code = 108;//请输入验证码
                return Send(resultResPonse);
            }
            if (string.IsNullOrEmpty(verifycode))
            {
                resultResPonse.code = 0;//请输入新密码
                resultResPonse.data = "请输入新密码";
                return Send(resultResPonse);
            }
            try
            {
                resultResPonse = VerifyMobileVerifyCodeByType(UserInfo.Mobile, verifycode, "2");//验证短信是否正确
                if (resultResPonse.code != 1)
                {
                    return Send(resultResPonse);
                }
                //修改密码
                UserResponse userRes = Uranus.Service.User.GetUser().UpdatePasswordByMobile(new UserRequest()
                {
                    UserDto = new UserDTO()
                    {
                        Mobile = UserInfo.Mobile,
                        PassWord = password
                    }
                });
                if (userRes != null && userRes.Code == 1)
                {
                    resultResPonse.code = 1;
                    SourceHandle(SourceOperation.EditPwd, string.Empty, UserInfo.UserID, Uranus.Common.Validates.GetInt(GetParmsKey<string>("sourceTypeId")));
                }
                else
                {
                    resultResPonse.data = "修改失败，请稍后再试";
                    LogHelper.WriteLogError("用户" + UserInfo.Mobile + "修改登录密码失败", "失败原因:" + userRes.ResposeData, false);
                    resultResPonse.code = 5;
                }
            }
            catch (Exception ex)
            {
                resultResPonse.data = "修改失败，请稍后再试";
                LogHelper.WriteLogError("用户" + UserInfo.Mobile + "修改登录密码失败", "失败原因:" + ex.Message, false);
                resultResPonse.code = 5;
            }
            return Send(resultResPonse);
        }

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultResPonse FindPassWord()
        {
            string mobile = GetParmsKey<string>("mobile");
            string verifycode = GetParmsKey<string>("verifycode");
            string password = GetParmsKey<string>("password");
            if (string.IsNullOrEmpty(mobile))
            {
                resultResPonse.code = 106;//请输入手机号
                return Send(resultResPonse);
            }
            if (string.IsNullOrEmpty(verifycode))
            {
                resultResPonse.code = 108;//请输入验证码
                return Send(resultResPonse);
            }
            if (string.IsNullOrEmpty(verifycode))
            {
                resultResPonse.code = 5;//请输入新密码
                resultResPonse.data = "请输入新密码";
                return Send(resultResPonse);
            }
            try
            {
                resultResPonse = VerifyMobileVerifyCodeByType(mobile, verifycode, "3");//验证短信是否正确
                if (resultResPonse.code != 1)
                {
                    resultResPonse.data = "请输入正确的短信验证码";
                    return Send(resultResPonse);
                }
                //修改密码
                UserResponse userRes = Uranus.Service.User.GetUser().UpdatePasswordByMobile(new UserRequest()
                {
                    UserDto = new UserDTO()
                    {
                        Mobile = mobile,
                        PassWord = password
                    }
                });
                if (userRes != null && userRes.Code == 1)
                {
                    CacheKey cacheKey = CacheItem.InitByIdentity(mobile, "modifypassword").User.Other;
                    CacheRedis.DelCacheKey(cacheKey);
                    resultResPonse.code = 1;
                }
                else
                {
                    resultResPonse.data = "修改失败，请稍后再试";
                    LogHelper.WriteLogError("用户" + mobile + "密码找回修改密码失败", "失败原因:" + userRes.ResposeData, false);
                    resultResPonse.code = 5;
                }
            }
            catch (Exception ex)
            {
                resultResPonse.data = "修改失败，请稍后再试";
                LogHelper.WriteLogError("用户" + mobile + "密码找回修改密码失败", "失败原因:" + ex.Message, false);
                resultResPonse.code = 5;
            }
            return Send(resultResPonse);
        }
        #endregion

        #region 修改登录手机号
        /// <summary>
        /// 更换用户手机号
        /// Date:2017-10-20 00:00:00
        /// Author:Linsan
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UserState(VisitUserStateEnum = VisitUserStateEnum.MustLogin)]
        public ResultResPonse UpdateMobile()
        {
            string mobile = GetParmsKey<string>("mobile");
            string oldcode = GetParmsKey<string>("oldcode");
            string newcode = GetParmsKey<string>("newcode");

            if (string.IsNullOrEmpty(mobile) || string.IsNullOrEmpty(oldcode) || string.IsNullOrEmpty(newcode))
            {
                resultResPonse.code = 3;
                return Send(resultResPonse);
            }
            ResultResPonse verifyOldCode = VerifyMobileVerifyCodeByType(UserInfo.Mobile, oldcode, "4");
            if (verifyOldCode.code == 109)
            {
                resultResPonse.code = 0;
                resultResPonse.data = "请先获取验证码";
                return Send(resultResPonse);
            }
            if (verifyOldCode.code == 111)
            {
                resultResPonse.code = 0;
                resultResPonse.data = "请输入正确的短信验证码";
                return Send(resultResPonse);
            }
            ResultResPonse verifyNewCode = VerifyMobileVerifyCodeByType(mobile, newcode, "5");
            if (verifyNewCode.code == 109)
            {
                resultResPonse.code = 0;
                resultResPonse.data = "请先获取验证码";
                return Send(resultResPonse);
            }
            if (verifyNewCode.code == 111)
            {
                resultResPonse.code = 0;
                resultResPonse.data = "请输入正确的短信验证码";
                return Send(resultResPonse);
            }
            UserResponse userRes = Uranus.Service.User.GetUser().GetUserDTOByMobile(mobile);
            if (userRes.Code == 1 && userRes.UserDto != null)
            {
                resultResPonse.code = 107;
                return Send(resultResPonse);
            }

            UserResponse response = Uranus.Service.User.GetUser().UpdateMobileByUserID(new UserRequest
            {
                UserDto = new UserDTO
                {
                    Mobile = mobile,
                    UserID = UserInfo.UserID
                }
            });
            if (response != null && response.Code == 1)
            {
                SourceHandle(SourceOperation.EditMobile, string.Empty, UserInfo.UserID, Uranus.Common.Validates.GetInt(GetParmsKey<string>("sourceTypeId")));
                CacheRedis.DelCacheKey(CacheItem.InitByIdentity(UserInfo.UserID + "", "GetUserByUserID").User.Info);
                resultResPonse.code = 001;
                return Send(resultResPonse);
            }
            resultResPonse.code = 006;
            return Send(resultResPonse);
        }

        #endregion
    }
}
